package com.yyx.up.producer.bean;

import com.yyx.up.common.bean.DataIn;
import com.yyx.up.common.bean.DataOut;
import com.yyx.up.common.bean.Producer;
import com.yyx.up.common.util.DateUtil;
import com.yyx.up.common.util.NumberUtil;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Description: 本地数据文件生产者
 * @Author: yyx
 * @Create: 2023/4/10 11:16
 * @Version: 8
 */
public class LocalFileProducer implements Producer {
    private DataIn in;
    private DataOut out;
    private volatile boolean flg = true;//增强内存可见性，在别的线程中改变了它的属性可以及时察觉

    public void setIn(DataIn in) {
        this.in = in;
    }

    public void setOut(DataOut out) {
        this.out = out;
    }

    /**
     * 生产数据
     */
    public void produce() {
        try{
            //读取用户、电影类型数据
            List<User> users = in.read(User.class);
            List<Film> films = in.read2(Film.class);
            while (flg){//读取是一次，生成是多次
                // 从用户数据中随机1个电话号码
                int userIndex = new Random().nextInt(users.size());
                // 从电影类型数据中随机1个电影类型编号
                int filmIndex = new Random().nextInt(films.size());
                User user = users.get(userIndex);
                Film film = films.get(filmIndex);
                // 生成随机的观影时间 !DateUtil方法
                String startData = "20220101000000";
                String endData = "20230101000000";
                long startTime = DateUtil.parse(startData,"yyyyMMddHHmmss").getTime();
                long endTime = DateUtil.parse(endData,"yyyyMMddHHmmss").getTime();
                long watchTime = startTime + (long)((endTime - startTime) * Math.random());//观影时间一定在2022到2023之间
                String watchTimeString = DateUtil.format(new Date(watchTime),"yyyyMMddHHmmss");//通话时间字符串
                // 生成随机的观影时长 !NumberUtil方法
                String duration = NumberUtil.format(new Random().nextInt(9999),4);//0189使得长度固定
                // 生成观影记录
                WatchLog watchLog = new WatchLog(user.getTel(),film.getFilm(),watchTimeString,duration);
                System.out.println(watchLog);
                // 将观影记录刷写到数据文件中
                out.write(watchLog);
                Thread.sleep(500);//生成一条休眠0.5s
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭生产者
     * @throws IOException
     */
    public void close() throws IOException {
        if(in != null){
            in.close();
        }
        if(out != null){
            out.close();
        }
    }
}
